#include "helicopterform.h"
#include "ui_helicopterform.h"
#include "helicopter.h"
#include "heltimer.h"
#include "wagon.h"
#include "scorebutton.h"
#include "person.h"
#include "blood.h"
#include "pertimer.h"
#include "bloodtimer.h"
#include <QPainter>
#include <QPixmap>
#include <QtGui>
#include <QLabel>

HelicopterForm::HelicopterForm(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::HelicopterForm)
{
    ui->setupUi(this);

    // Create the "PAUSED" label
    CreatePausedLabel();

    // Game starts out running
    isPaused = false;

    // Initialize number of saved people
    numSaved = 0;

    // Set up difficulty level at medium
    SetMed();

    // Make a helicopter, wagon, and scoreboard
    CreateHelicopter();
    CreateWagon();
    CreateScoreButton();

    // Set up background image
    MatchRatio();
    this->setFixedSize(this->width(), this->height());

    DisableScreenResolutions();

    // Set up our ID givers
    for (int i = 0; i < 100; ++i)
    {
        perID[i] = false;
        bldID[i] = false;
    }

    // Log construct
    LogEvent("Game Created");
}

HelicopterForm::~HelicopterForm()
{
    delete ui;
}

// Quit the program
void HelicopterForm::on_actionQuit_activated()
{
    qApp->quit();
    LogEvent("Game Quit");
}

// Disable Screen resolutions
void HelicopterForm::DisableScreenResolutions()
{
    QRect geo = QApplication::desktop()->screenGeometry(QApplication::desktop()->screenNumber());
    int height = geo.height();
    int width = geo.width();

    // do some type of loop that will loop through resolutions and disable the ones with height larger than "height"
    if (height < 1920)
        ui->action2560_x_1920->setDisabled(true);

    if (height < 1600)
        ui->action2560_x_1600->setDisabled(true);

    if (height < 1200 && width < 1920)
        ui->action1920_x_1201->setDisabled(true);

    if (height < 1080 && width < 1920)
        ui->action1920_x_1080->setDisabled(true);

    if (height < 1050 && width < 1680)
        ui->action1680_x_1050->setDisabled(true);

    if (height < 1200 && width < 1600)
        ui->action1600_x_1200->setDisabled(true);

    if (height < 900 && width < 1440)
        ui->action1440_x_900->setDisabled(true);

    if (height < 768 && width < 1366)
        ui->action1366_x_768->setDisabled(true);

    if (height < 768 && width < 1360)
        ui->action1360_x_768->setDisabled(true);

    if (height < 1024 && width < 1280)
        ui->action1280_x_1024->setDisabled(true);

    if (height < 768 && width < 1024)
        ui->action1024_x_768->setDisabled(true);
}

// Toggle Fullscreen
void HelicopterForm::on_actionEnter_Fullscreen_activated()
{
    ToggleFullScreen();
}

void HelicopterForm::ToggleFullScreen()
{
    // if not in fullscreen
    if (this->isFullScreen() == false)
    {
        // Go fullscreen
        this->showFullScreen();

        MatchRatio();

        // Update the menu item
        if (this->isFullScreen() == true)
        {
            ui->actionEnter_Fullscreen->setText("Exit Fullscreen");
            ui->menuSet_Resolution->setDisabled(true);
        }
    // it was in fullscreen so we exit fullscreen
    } else // exit fullscreen
    {
        this->showNormal();
        MatchRatio();
        ui->actionEnter_Fullscreen->setText("Enter Fullscreen");
        ui->menuSet_Resolution->setDisabled(false);
    }
    LogEvent("Fullscreen Toggled");
}

// Match background to aspect ratio
void HelicopterForm::MatchRatio()
{
    // Find form's width and height
    int width = this->width();
    int height = this->height();


    // Create a QString to use with GetFilePath
    QString s;

    // Check which image to load
    int ratio = (width * 10) / height; // find a ratio to match this to

    switch (ratio) // Pick which background image to load
    {
        case 17: // 16:9 ratio
            s = GetFilePath("images/1920x1080.jpg");
            SetBackground(s);
            //SetBackground("./images/1920x1080.jpg");
            break;
        case 16: // 16:10 ratio
            s = GetFilePath("images/2560x1600.jpg");
            SetBackground(s);
            //SetBackground("./images/2560x1600.jpg");
            break;
        case 13: // 4:3 ratio
            s = GetFilePath("images/1600x1200.jpg");
            SetBackground(s);
            //SetBackground("./images/1600x1200.jpg");
            break;
        case 12: // 5:4 ratio
            s = GetFilePath("images/1280x1024.jpg");
            SetBackground(s);
            //SetBackground("./images/1280x1024.jpg");
            break;
        default: // revert to base size because resolution was not supported
            this->showNormal();
            QRect rect;
            rect.setWidth(800);
            rect.setHeight(600);
            this->setGeometry(rect);
            this->setFixedSize(rect.width(), rect.height());
            MatchRatio();
            break;
    }

    // Reset the wagon
    ResetWagon();

    // Reset the scoreboard
    ResetScoreButton();

    // Reset the PausedLabel (possibly hidden)
    ResetPausedLabel();

    LogEvent("Resolution Set");
}

// Set the background to the window size
void HelicopterForm::SetBackground(QString filepath)
{
    QPalette pal = this->palette();
    pal.setBrush(QPalette::Window, QPixmap(filepath).scaled(this->size()));
    this->setPalette(pal);
}

// *** SUPPORT RESOLUTIONS *** //
void HelicopterForm::on_action800_x_600_activated()
{
    SetResolution(800, 600);
}

void HelicopterForm::on_action1024_x_768_activated()
{
    SetResolution(1024, 768);
}

void HelicopterForm::on_action1280_x_1024_activated()
{
    SetResolution(1280, 1024);
}

void HelicopterForm::on_action1360_x_768_activated()
{
    SetResolution(1360, 768);
}

void HelicopterForm::on_action1366_x_768_activated()
{
    SetResolution(1366, 768);
}

void HelicopterForm::on_action1440_x_900_activated()
{
    SetResolution(1440, 900);
}

void HelicopterForm::on_action1600_x_1200_activated()
{
    SetResolution(1600, 1200);
}

void HelicopterForm::on_action1680_x_1050_activated()
{
    SetResolution(1680, 1050);
}

void HelicopterForm::on_action1920_x_1080_activated()
{
    SetResolution(1920, 1080);
}

void HelicopterForm::on_action1920_x_1201_activated()
{
    SetResolution(1920, 1200);
}

void HelicopterForm::on_action2560_x_1600_activated()
{
    SetResolution(2560, 1600);
}

void HelicopterForm::on_action2560_x_1920_activated()
{
    SetResolution(2560, 1920);
} // *** END SUPPRT RESOLUTIONS *** //

// Set up the resolution
void HelicopterForm::SetResolution(int x, int y)
{
    if (this->isFullScreen() == false)
    {
        QRect rect = this->geometry();
        rect.setWidth(x);
        rect.setHeight(y);
        this->setGeometry(rect);
        this->setFixedSize(rect.width(), rect.height());
        MatchRatio();
    }
}

// Creates the Helicopter object
void HelicopterForm::CreateHelicopter()
{
    Helicopter *heli = new Helicopter(this);
    heli->show();
    LogEvent("Helicopter Created");
}

// Reset the helicopter to the upper left hand corner
void HelicopterForm::ResetHelicopter() // is called in the inc in heltimer
{
    Helicopter *temp = this->findChild<Helicopter*>("helicopter");
    temp->setGeometry(15, 30, 120, 50); // same as in helicopter constructor
    temp->SetHelicopterMovie("images/heliright.mng", false);
    HelTimer *tempTimer = this->findChild<HelTimer*>("helicoptertimer");
    tempTimer->SetAction(0);

    LogEvent("Helicopter Reset");
}

// Process the left and right arrow buttons being pushed
void HelicopterForm::keyPressEvent(QKeyEvent *event)
{
    switch (event->key())
    {
    case Qt::Key_Left: // start left move
        {
            WagonTimer *tmpTmr = this->findChild<WagonTimer*>("wagontimer");
            tmpTmr->MoveLeft();
        }
        break;
    case Qt::Key_Right: // start right move
        {
            WagonTimer *tmpTmr = this->findChild<WagonTimer*>("wagontimer");
            tmpTmr->MoveRight();
        }
        break;
    case Qt::Key_P: //Pauses the game
        {
            if (isPaused == false)
                PauseGame();
            else
                ResumeGame();
        }
        break;
    default: // do nothing
        break;
    }
}

// Process the left and right arrow buttons being released
void HelicopterForm::keyReleaseEvent(QKeyEvent *event)
{
    switch (event->key())
    {
    case Qt::Key_Left: // stop left move
        {
            WagonTimer *tmpTmr = this->findChild<WagonTimer*>("wagontimer");
            tmpTmr->StopMove();
        }
        break;
    case Qt::Key_Right: // stop right move
        {
            WagonTimer *tmpTmr = this->findChild<WagonTimer*>("wagontimer");
            tmpTmr->StopMove();
        }
        break;
    default: // do nothing
        break;
    }
}

// Create a wagon
void HelicopterForm::CreateWagon()
{
    Wagon *wag = new Wagon(this, (this->width() / 2), this->height());
    wag->show();

    LogEvent("Wagon Created");
}

// Reset the wagon (for screensize change problems)
void HelicopterForm::ResetWagon()
{
    Wagon *temp = this->findChild<Wagon*>("wagon");
    temp->setGeometry((this->width() / 2) - 38, this->height() - temp->height(), 75, 35);

    LogEvent("Wagon Reset");
}

// Create a scoreboard
void HelicopterForm::CreateScoreButton()
{
    ScoreButton *score = new ScoreButton(this, this->width() - 160, this->height() - 120);
    score->show();
    SetScore();

    LogEvent("Scoreboard Created");
}

// Reset the scoreboard's position
void HelicopterForm::ResetScoreButton()
{
    ScoreButton *temp = this->findChild<ScoreButton*>("scorebutton");
    temp->setGeometry(this->width() - 160, this->height() - 120, 120, 80); // from constructer in class

    LogEvent("Scoreboard Reset");
}

// Set score
void HelicopterForm::SetScore()
{
    ScoreButton *temp = this->findChild<ScoreButton*>("scorebutton");
    temp->setText(QString::number(numSaved));
}

// Increment Number of saved People
void HelicopterForm::IncNumSaved()
{
    ++numSaved;
    SetScore();
    LogEvent("Score Incremented");
}

// Decrement Number of saved People
void HelicopterForm::DecNumSaved()
{
    --numSaved;
    SetScore();
    LogEvent("Score Decremented");
}

// Set the difficulty to be easy
void HelicopterForm::SetEasy()
{
    helSpeed = 1;
    perSpeed = 2;
    dropLow = 4000;
    dropHigh = 7000;

    // Mess with menu options
    ui->actionEasy->setDisabled(true);
    ui->actionMedium->setDisabled(false);
    ui->actionHard->setDisabled(false);
    ui->actionCheat_Mode->setDisabled(false);
}

// Set the difficulty to be medium
void HelicopterForm::SetMed()
{
    helSpeed = 2;
    perSpeed = 4;
    dropLow = 2000;
    dropHigh = 4000;

    // Mess with menu options
    ui->actionEasy->setDisabled(false);
    ui->actionMedium->setDisabled(true);
    ui->actionHard->setDisabled(false);
    ui->actionCheat_Mode->setDisabled(false);
}

// Set the difficulty to be hard
void HelicopterForm::SetHard()
{
    helSpeed = 3;
    perSpeed = 6;
    dropLow = 500;
    dropHigh = 2000;

    // Mess with menu options
    ui->actionEasy->setDisabled(false);
    ui->actionMedium->setDisabled(false);
    ui->actionHard->setDisabled(true);
    ui->actionCheat_Mode->setDisabled(false);
}

// Set the difficulty to cheat mode :D
void HelicopterForm::SetCheat()
{
    helSpeed = 0;
    perSpeed = 6;
    dropLow = 50;
    dropHigh = 50;

    // Mess with menuy options
    ui->actionEasy->setDisabled(false);
    ui->actionMedium->setDisabled(false);
    ui->actionHard->setDisabled(false);
    ui->actionCheat_Mode->setDisabled(true);
}

// Handle the "Easy" Button
void HelicopterForm::on_actionEasy_activated()
{
    SetEasy();
    LogEvent("Difficulty Set to Easy");
}

// Handle the "Medium" Button
void HelicopterForm::on_actionMedium_activated()
{
    SetMed();
    LogEvent("Difficulty Set to Medium");
}

// Handle the "Hard" Button
void HelicopterForm::on_actionHard_activated()
{
    SetHard();
    LogEvent("Difficulty Set to Hard");
}

// Handle the "Cheat Mode" Button
void HelicopterForm::on_actionCheat_Mode_activated()
{
    SetCheat();
    LogEvent ("Difficulty Set to Cheat Mode you cheater you!");
}

// Find an available slot to use as a person object ID
int HelicopterForm::GetFreeObjectID()
{
    for (int i = 0; i < 100; ++i)
    {
        if (perID[i] == false)
        {
            perID[i] = true;
            return i;
        }
    }
}

// Find an available slot to use as a blood object ID
int HelicopterForm::GetFreeBloodID()
{
    for (int i = 0; i < 100; ++i)
    {
        if (bldID[i] == false)
        {
            bldID[i] = true;
            return i;
        }
    }
}

// Delete a person and its timer
void HelicopterForm::DeletePersonAndTimer(QString obID)
{
    Person *temp = this->findChild<Person*>(obID);
    temp->deleteLater();
    PerTimer *tempTimer = this->findChild<PerTimer*>(obID + "t");
    tempTimer->deleteLater();
    obID.resize(obID.length() - 1);
    perID[obID.toInt()] = false;
    LogEvent("Person and Timer Reset");
}

// Delete blood and its timer
void HelicopterForm::DeleteBloodAndTimer(QString obID)
{
    Blood *temp = this->findChild<Blood*>(obID);
    temp->deleteLater();
    BloodTimer *tempTimer = this->findChild<BloodTimer*>(obID + "t");
    tempTimer->deleteLater();
    obID.resize(obID.length() - 1);
    bldID[obID.toInt()] = false;
    LogEvent("Blood and Timer Reset");
}

// Pause game (freeze everything and display "PAUSED" on the screen)
void HelicopterForm::PauseGame()
{
    LogEvent("Game Paused");

    isPaused = true; // flip the bool
    ui->actionPause->setText("Resume");

    // stop the helicopter
    HelTimer *tmpHelTimer = this->findChild<HelTimer*>("helicoptertimer");
    tmpHelTimer->stop();
    Helicopter *tmpHeli = this->findChild<Helicopter*>("helicopter");
    tmpHeli->animMovie->setPaused(true);
    DropTimer *tmpDrpTmr = this->findChild<DropTimer*>("droptimer");
    tmpDrpTmr->stop();

    // stop all the people
    for (int i = 0; i < 100; ++i)
    {
        Person *temp = this->findChild<Person*>(QString::number(i) + "p");

        if (temp) // if the person exists
        {
            temp->animMovie->setPaused(true);
            PerTimer *tmpPerTimer = this->findChild<PerTimer*>(QString::number(i) + "pt");
            tmpPerTimer->stop();
        }
    }

    // stop all the blood
    for (int i = 0; i < 100; ++i)
    {
        Blood *temp = this->findChild<Blood*>(QString::number(i) + "b");

        if (temp) // if the person exists
        {
            temp->animMovie->setPaused(true);
            BloodTimer *tmpBldTimer = this->findChild<BloodTimer*>(QString::number(i) + "bt");
            tmpBldTimer->stop();
        }
    }

    // freeze the wagon
    WagonTimer *tmpWagTimer = this->findChild<WagonTimer*>("wagontimer");
    tmpWagTimer->stop();
    Wagon *tmpWag = this->findChild<Wagon*>("wagon");
    tmpWag->animMovie->setPaused(true);

    // display "PAUSED"
    QLabel *tempPausedLabel = this->findChild<QLabel*>("pausedlabel");
    tempPausedLabel->show();
}

// Resume game (unfreeze everything and hide "PAUSED" on the screen)
void HelicopterForm::ResumeGame()
{
    LogEvent("Game Resumed");

    isPaused = false; // flip the bool
    ui->actionPause->setText("Pause");

    // free the helicopter
    HelTimer *tmpHelTimer = this->findChild<HelTimer*>("helicoptertimer");
    tmpHelTimer->start();
    Helicopter *tmpHeli = this->findChild<Helicopter*>("helicopter");
    tmpHeli->animMovie->setPaused(false);
    DropTimer *tmpDrpTmr = this->findChild<DropTimer*>("droptimer");
    tmpDrpTmr->start();

    // free all the people
    for (int i = 0; i < 100; ++i)
    {
        Person *temp = this->findChild<Person*>(QString::number(i) + "p");

        if (temp) // if the person exists
        {
            temp->animMovie->setPaused(false);
            PerTimer *tmpPerTimer = this->findChild<PerTimer*>(QString::number(i) + "pt");
            tmpPerTimer->start();
        }
    }

    // free all the blood
    for (int i = 0; i < 100; ++i)
    {
        Blood *temp = this->findChild<Blood*>(QString::number(i) + "b");

        if (temp) // if the person exists
        {
            temp->animMovie->setPaused(false);
            BloodTimer *tmpBldTimer = this->findChild<BloodTimer*>(QString::number(i) + "bt");
            tmpBldTimer->start();
        }
    }

    // free the wagon
    WagonTimer *tmpWagTimer = this->findChild<WagonTimer*>("wagontimer");
    tmpWagTimer->start();
    Wagon *tmpWag = this->findChild<Wagon*>("wagon");
    tmpWag->animMovie->setPaused(false);

    // hide "PAUSED"
    QLabel *tempPausedLabel = this->findChild<QLabel*>("pausedlabel");
    tempPausedLabel->hide();
}

// Pause button
void HelicopterForm::on_actionPause_activated()
{
    if (isPaused == false) // only pause if running
    {
        PauseGame();
    }
    else // resume a paused game
    {
        ResumeGame();
    }
}

// Create the paused label (this is called in constructor)
void HelicopterForm::CreatePausedLabel()
{
    QLabel *pausedLabel = new QLabel(this);
    pausedLabel->setParent(this);
    pausedLabel->setObjectName("pausedlabel");
    pausedLabel->setGeometry((this->width() / 2) - 150, (this->height() / 2) - 50, 300, 100);
    pausedLabel->setText("PAUSED");
    pausedLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    pausedLabel->setStyleSheet("QLabel { \n color: rgba(40,40,40,200); \n font-size: 36pt; \n }");
    pausedLabel->hide();

    LogEvent("Paused Label Created");
}

// Resets the geometry of the paused label whenever the screen is resized
void HelicopterForm::ResetPausedLabel()
{
    QLabel *pausedLabel = this->findChild<QLabel*>("pausedlabel");
    pausedLabel->setGeometry((this->width() / 2) - 150, (this->height() / 2) - 50, 300, 100);

    LogEvent("Paused Label Reset");
}

// Save the game to a file
void HelicopterForm::on_actionSave_activated()
{
    LogEvent("Game Saved");

    // Pauses the game when you click on "save"
    if (isPaused == false)
    {
        this->PauseGame();
    }

    // Begin saving
    QString filename = QFileDialog::getSaveFileName(this, "Save Form", "", "");
    QFile file(filename);

    if (!file.open(QIODevice::WriteOnly))
    {
        QMessageBox::information(this, tr("Unable to open file"), file.errorString());
        return;
    }

    QDataStream out(&file);
    out.setVersion(QDataStream::Qt_4_6); // Change this based on current Qt version

    // save generic stuff on the form
    QList<Person*> perList = this->findChildren<Person*>();
    QList<Blood*> bldList = this->findChildren<Blood*>();
    out << this->isFullScreen();
    out << perList.length();
    out << bldList.length();
    out << numSaved;
    out << this->width();
    out << this->height();
    out << ui->actionEasy->isEnabled();
    out << ui->actionMedium->isEnabled();
    out << ui->actionHard->isEnabled();
    out << ui->actionCheat_Mode->isEnabled();

    // save the helicopter and its timers
    Helicopter *tmpHeli = this->findChild<Helicopter*>("helicopter");
    HelTimer *tmpHelTimer = this->findChild<HelTimer*>("helicoptertimer");
    DropTimer *tmpDrpTmr = this->findChild<DropTimer*>("droptimer");
    out << tmpHeli->geometry();
    out << tmpHeli->animMovie->fileName();
    out << tmpHeli->animMovie->speed();
    out << tmpHeli->animMovie->currentFrameNumber();
    out << tmpHelTimer->GetAction();
    out << tmpDrpTmr->interval();

    // save the wagon and its timer
    Wagon *tmpWag = this->findChild<Wagon*>("wagon");
    WagonTimer *tmpWagTimer = this->findChild<WagonTimer*>("wagontimer");
    out << tmpWag->geometry();
    out << tmpWag->animMovie->fileName();
    out << tmpWag->animMovie->currentFrameNumber();
    out << tmpWagTimer->GetAction();

    // save all the people and their timers
    for (int i = 0; i < 100; ++i)
    {
        Person *perTmp = this->findChild<Person*>(QString::number(i) + "p");
        if (perTmp)
        {
            PerTimer *perTmrTmp = this->findChild<PerTimer*>(QString::number(i) + "pt");
            out << perTmp->geometry();
            out << perTmp->animMovie->fileName();
            out << perTmp->animMovie->currentFrameNumber();
            out << perTmrTmp->GetAction();
        }
    }

    // save the blood and the bloodtimers
    for (int i = 0; i < 100; ++i)
    {
        Blood *bldTmp = this->findChild<Blood*>(QString::number(i) + "b");
        if (bldTmp)
        {
            out << bldTmp->geometry();
            out << bldTmp->animMovie->fileName();
            out << bldTmp->animMovie->currentFrameNumber();
        }
    }

    file.close();
}

// Load the game from a file
void HelicopterForm::on_actionLoad_activated()
{
    // Pauses the game when you click on "load"
    if (isPaused == false)
    {
        this->PauseGame();
    }

    // Delete all dynamic objects
    DeleteDynamic();

    // Begin Loading
    QString filename = QFileDialog::getOpenFileName(this, "Load Form", "", "");

    if (filename != "")
    {
        QFile file(filename);

        if (!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::information(this, tr("Unable to open file"), file.errorString());
            return;
        }

        QDataStream in(&file);
        //in.setVersion(QDataStream::Qt_4_6);

        // set up all the variables
        bool newIsFullScreen; // form stuff
        int newCount;
        int newBloodCount;
        int newNumSaved;
        int newWidth;
        int newHeight;
        bool newEasy;
        bool newMed;
        bool newHard;
        bool newCheat;
        QRect heliGeo; // helicopter stuff
        QString heliLink;
        int heliSpeed;
        int heliFrameNum;
        int heliAction;
        int heliInterval;
        QRect wagGeo; // wagon stuff
        QString wagLink;
        int wagFrameNum;
        int wagAction;
        QRect perGeo; // person stuff
        QString perLink;
        int perFrameNum;
        int perAction;
        QRect bldGeo; // blood stuff
        QString bldLink;
        int bldFrameNum;

        // Load generic stuff on the form
        in >> newIsFullScreen;
        in >> newCount;
        in >> newBloodCount;
        in >> newNumSaved;
        in >> newWidth;
        in >> newHeight;
        in >> newEasy;
        in >> newMed;
        in >> newHard;
        in >> newCheat;


        numSaved = newNumSaved;
        SetScore(); // update the score
        // mess with fullscreen and window size
        if (newIsFullScreen == false)
        {
            if (this->isFullScreen() == true)
            {
                ToggleFullScreen();
            }
            SetResolution(newWidth, newHeight);
        } else
        {
            if (this->isFullScreen() == false)
            {
                ToggleFullScreen();
            }
        }
        // set difficulty level
        if (newEasy == false)
        {
            SetEasy();
        } else if (newMed == false)
        {
            SetMed();
        } else if (newHard == false)
        {
            SetHard();
        }
        else if (newCheat == false)
        {
            SetCheat();
        }

        // load the helicopter stuff
        Helicopter *tmpHeli = this->findChild<Helicopter*>("helicopter");
        HelTimer *tmpHelTimer = this->findChild<HelTimer*>("helicoptertimer");
        DropTimer *tmpDrpTmr = this->findChild<DropTimer*>("droptimer");

        in >> heliGeo;
        in >> heliLink;
        in >> heliSpeed;
        in >> heliFrameNum;
        in >> heliAction;
        in >> heliInterval;

        tmpHeli->setGeometry(heliGeo);
        tmpHeli->SetHelicopterMovie(heliLink, true);
        tmpHeli->animMovie->setSpeed(heliSpeed);
        for (int i = 0; i < heliFrameNum; ++i) // loop to get it to the right frame
        {
            tmpHeli->animMovie->jumpToNextFrame();
        }
        tmpHeli->animMovie->setPaused(true);
        tmpHelTimer->SetAction(heliAction);
        tmpDrpTmr->setInterval(heliInterval);

        // load the wagon stuff
        Wagon *tmpWag = this->findChild<Wagon*>("wagon");
        WagonTimer *tmpWagTimer = this->findChild<WagonTimer*>("wagontimer");

        in >> wagGeo;
        in >> wagLink;
        in >> wagFrameNum;
        in >> wagAction;

        tmpWag->setGeometry(wagGeo);
        tmpWag->SetWagonMovie(wagLink);
        for (int i = 0; i < wagFrameNum; ++i) // loop to get it to the right frame
        {
            tmpWag->animMovie->jumpToNextFrame();
        }
        tmpWag->animMovie->setPaused(true);
        tmpWagTimer->SetAction(wagAction);

        // load all the people and their timers
        for (int i = 0; i < newCount; ++i)
        {
            Person *perTmp = new Person(this, 5, 5);
            PerTimer *perTmrTmp = this->findChild<PerTimer*>(QString::number(i) + "pt");

            in >> perGeo;
            in >> perLink;
            in >> perFrameNum;
            in >> perAction;

            perTmp->setGeometry(perGeo);
            perTmp->SetPersonMovie(perLink);
            for (int i = 0; i < perFrameNum; ++i) // loop to get it to the right frame
            {
                perTmp->animMovie->jumpToNextFrame();
            }
            perTmp->animMovie->setPaused(true);
            perTmrTmp->SetAction(perAction);
            perTmp->show();
            perTmrTmp->stop();
        }

        // load all the blood and their timers
        for (int i = 0; i < newCount; ++i)
        {
            Blood *bldTmp = new Blood(this, 5, 5);
            BloodTimer *bldTmrTmp = this->findChild<BloodTimer*>(QString::number(i) + "bt");

            in >> bldGeo;
            in >> bldLink;
            in >> bldFrameNum;

            bldTmp->setGeometry(bldGeo);
            bldTmp->SetBloodMovie(bldLink);
            for (int i = 0; i < bldFrameNum; ++i) // loop to get it to the right frame
            {
                bldTmp->animMovie->jumpToNextFrame();
            }
            bldTmp->animMovie->setPaused(true);
            bldTmp->show();
            bldTmrTmp->stop();
        }

        file.close();
    }
    LogEvent("Game Loaded");
}

// Delete all dynamic objects
void HelicopterForm::DeleteDynamic()
{
    // Delete all dynamic objects
    for (int i = 0; i < 100; ++i) // delete the people and people timers
    {
        Person *perTmp = this->findChild<Person*>(QString::number(i) + "p");

        if (perTmp)
        {
            PerTimer *perTmrTmp = this->findChild<PerTimer*>(QString::number(i) + "pt");
            perTmp->setObjectName("todelete");
            perTmrTmp->setObjectName("todelete");
            perTmrTmp->deleteLater();
            perTmp->deleteLater();
            delete perTmrTmp;
        }
        perID[i] = false;
    }
    for (int i = 0; i < 100; ++i) // delete the blood and blood timers
    {
        Blood *bldTmp = this->findChild<Blood*>(QString::number(i) + "b");

        if (bldTmp)
        {
            BloodTimer *bldTmrTmp = this->findChild<BloodTimer*>(QString::number(i) + "bt");
            bldTmp->setObjectName("todelete");
            bldTmrTmp->setObjectName("todelete");
            bldTmrTmp->deleteLater();
            bldTmp->deleteLater();
        }
        bldID[i] = false;
    }
}

// write out a log to a file
void HelicopterForm::LogEvent(QString log)
{
    QFile file("log.txt");
    file.open(QIODevice::Append | QIODevice::Text);
    QTextStream out(&file);
    out << log << endl;
    file.close();
}

// Returns the absolute file path so the game can run from any directory --- not fully working yet
QString HelicopterForm::GetFilePath(QString path)
{
     QDir dir(path);
     QString s, t;
     bool escape = true;

     if (dir.exists(path) == true) //if the directory exists here
        s = dir.absolutePath();    //set the path
     else
     {
         t = dir.absolutePath();
         while (dir.exists(t) == false && escape == true) // move toward the base of the directory tree
         {
            escape = dir.cdUp();
         }

         s = dir.absolutePath();
     }

     LogEvent(s);
     return s;
}

void HelicopterForm::loadSavedGame() {
    this->on_actionLoad_activated();
}
